package practise;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import practise.APIResponse.Status;


public class CenterRepository {
	
	public static Center get(String centerName) {
		
		try {
			String sql = "select id, center from centers where center = ?";
			
			Center center = null;
			
			try (Connection connection = DriverManager.getConnection(Utils.getCloudSqlURL())) {
				
				try (PreparedStatement ps = connection.prepareStatement(sql)) {
					
					ps.setString(1, centerName.toLowerCase());
					
					try (ResultSet resultSet = ps.executeQuery()) {						
						while (resultSet.next()) {
							center = new Center();
							center.id = resultSet.getInt("id");
							center.name = resultSet.getString("center");
						}
					}
				}
			}
			
			return center;
			
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}		
	}
	
	public static Center add(String centerName) {
		
		try {
			String sql = "insert into centers values (0, ?)";			
			
			try (Connection connection = DriverManager.getConnection(Utils.getCloudSqlURL())) {
				
				try (PreparedStatement ps = connection.prepareStatement(sql)) {
					
					ps.setString(1, centerName.toLowerCase());
					
					ps.executeUpdate();					
				}
			}
			
			Center center = get(centerName);	
			return center;
			
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}		
	}
	
	public static void delete(String centerName) {
		
		Center center = get(centerName);
		
		if (null == center) 
			throw new APIException(Status.ERROR_RESOURCE_DOES_NOT_EXIST, 
					"Center [" + centerName + "] does not exist");
							
		try {
			String sql = "delete from centers where id = ?";			
			
			try (Connection connection = DriverManager.getConnection(Utils.getCloudSqlURL())) {
				
				try (PreparedStatement ps = connection.prepareStatement(sql)) {
					
					ps.setString(1, centerName.toLowerCase());
					
					ps.executeUpdate();					
				}
			}									
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}		
	}
}
